//##############################################################################
//#    CuteWebshot is an application which can be used to render
//#    screenshots from webpages.
//#
//#    Copyright (C) 2010  Juhapekka Piiroinen
//#
//#    This program is free software: you can redistribute it and/or modify
//#    it under the terms of the GNU General Public License as published by
//#    the Free Software Foundation, either version 3 of the License, or
//#    (at your option) any later version.
//#
//#    This program is distributed in the hope that it will be useful,
//#    but WITHOUT ANY WARRANTY; without even the implied warranty of
//#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//#    GNU General Public License for more details.
//#
//#    You should have received a copy of the GNU General Public License
//#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//#############################################################################
//# Contact: juhapekka.piiroinen@gmail.com
//#############################################################################
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    FUNC_IN;
        ui->setupUi(this);

        ///////////////////////////////////////
        // lets use proxy if available
        // works for windows and osx, but not un*x
        QNetworkProxyFactory::setUseSystemConfiguration(true);

        ///////////////////////////////////////
        // lets connect webview signals
        connect(ui->webView,SIGNAL(urlChanged(QUrl)),this,SLOT(handleUrlChanged(QUrl)));
        connect(ui->webView,SIGNAL(loadFinished(bool)),this,SLOT(handleLoadFinished(bool)));
        connect(ui->webView,SIGNAL(loadProgress(int)),this,SLOT(handleLoadProgress(int)));

        ///////////////////////////////////////
        // lets close application when rendering is done
        connect(this,SIGNAL(webshotReady()),this,SLOT(close()));

        ///////////////////////////////////////
        // we have also a kill switch if the rendering or downloading takes
        // too much time.
        QTimer::singleShot(MAX_RENDERING_TIME,this,SLOT(close()));
    FUNC_OUT;
}

void MainWindow::handleUrlChanged(QUrl url) {
    FUNC_IN;
        ui->label->setText(url.toString());
    FUNC_OUT;
}

void MainWindow::on_lineEdit_returnPressed() {
    FUNC_IN;
        setUrl(ui->lineEdit->text());
    FUNC_OUT;
}


void MainWindow::handleLoadProgress(int progress) {
    FUNC_IN;
        DEBUG << "progress:" << progress;
        if (progress==100) {
            ui->webView->stop();
        }
    FUNC_OUT;
}

void MainWindow::handleLoadFinished(bool ok) {
    FUNC_IN;
        if (ok==false) {
            FAIL << "ok==false";
            FUNC_OUT;
            return;
        }

        renderWebshot();
    FUNC_OUT;
}

MainWindow::~MainWindow()
{
    FUNC_IN;
        delete ui;
    FUNC_OUT;
}

void MainWindow::setUrl(QString url) {
    FUNC_IN;
        DEBUG << "url" << url;
        m_url = url;
        ui->lineEdit->setText(m_url);
        ui->webView->load(QUrl(m_url));
    FUNC_OUT;
}

void MainWindow::renderWebshot() {
    FUNC_IN;
        DEBUG << "Lets render the image from webview";

        ///////////////////////////////////////
        // lets get the current frame
        QWebFrame *mainFrame = ui->webView->page()->mainFrame();

        ///////////////////////////////////////
        // lets resize the viewport for full screen rendering
        ui->webView->page()->setViewportSize(mainFrame->contentsSize());

        ///////////////////////////////////////
        // lets initialize painter and the target image
        QPainter painter;
        QImage image(ui->webView->page()->viewportSize(), QImage::Format_ARGB32);

        ///////////////////////////////////////
        // lets paint the webpage to image
        DEBUG << "Lets render..";
        painter.begin(&image);
        mainFrame->render(&painter);
        painter.end();
        DEBUG << "..rendered!";

        ///////////////////////////////////////
        // lets save the image to png file using base64 encoding
        QSettings settings;
        QString path = settings.value(DEF_TARGET_PATH).toString();
        QDir directory(path);
        if (!directory.exists(path)) {
            if (!directory.mkdir(path)) {
                FAIL << "could not create directory" << directory.absolutePath();
            }
        }
        QString filename = path+m_url.toAscii().toBase64();
        image.save(filename+".png","png");
        QImage thumbnail = image.scaledToHeight(320);
        thumbnail.save(filename+".thumb.png","png");
        DEBUG << filename;

        ///////////////////////////////////////
        // lets save the current url as well, as we might have been redirected
        // we use Base64 in order to make it a bit more safe
        QFile fileCurrentUrl(filename+".url.txt");
        if (fileCurrentUrl.open(QIODevice::WriteOnly)) {
            fileCurrentUrl.write(ui->label->text().toAscii().toBase64());
            fileCurrentUrl.close();
        }

        ///////////////////////////////////////
        // lets save the html code also
        QFile fileHtmlCode(filename+".html.txt");
        if (fileHtmlCode.open(QIODevice::WriteOnly)) {
            fileHtmlCode.write(mainFrame->toHtml().toAscii().toBase64());
            fileHtmlCode.close();
        }

        ///////////////////////////////////////
        // lets save the plain text as well.
        QFile filePlainText(filename+".plain.txt");
        if (filePlainText.open(QIODevice::WriteOnly)) {
            filePlainText.write(mainFrame->toPlainText().toAscii().toBase64());
            filePlainText.close();
        }

        ///////////////////////////////////////
        // lets find all links in a tag
        QFile fileLinks(filename+".a.txt");
        if (fileLinks.open(QIODevice::WriteOnly)) {
            QWebElementCollection links = mainFrame->findAllElements("a");
            foreach (QWebElement linkElement, links) {
                QString href = linkElement.attribute("href");
                QString title = linkElement.toPlainText();
                fileLinks.write(QString("%0\t%1").arg(title).arg(href).toAscii().toBase64());
            }
            fileLinks.close();
        }

        ///////////////////////////////////////
        // lets find all src in img tags
        QFile fileImgs(filename+".img.txt");
        if (fileImgs.open(QIODevice::WriteOnly)) {
            QWebElementCollection imgs = mainFrame->findAllElements("img");
            foreach (QWebElement imgElement, imgs) {
                QString src = imgElement.attribute("src");
                QString alt = imgElement.attribute("alt");
                fileImgs.write(QString("%0\t%1").arg(alt).arg(src).toAscii().toBase64());
            }
            fileImgs.close();
        }

        ///////////////////////////////////////
        // lets find all type in script tags
        QFile fileScripts(filename+".script.txt");
        if (fileScripts.open(QIODevice::WriteOnly)) {
            QWebElementCollection scripts = mainFrame->findAllElements("script");
            foreach (QWebElement scriptElement, scripts) {
                QString src = scriptElement.attribute("src");
                QString type = scriptElement.attribute("type");
                QString lang = scriptElement.attribute("lang");
                QString language =  scriptElement.attribute("language");
                fileScripts.write(QString("%0\t%1\t%2\t%3").arg(type).arg(lang).arg(language).arg(src).toAscii().toBase64());
            }
            fileScripts.close();
        }

        ///////////////////////////////////////
        // lets find all src in iframe tags
        QFile fileIFrame(filename+".iframe.txt");
        if (fileIFrame.open(QIODevice::WriteOnly)) {
            QWebElementCollection iframes = mainFrame->findAllElements("iframe");
            foreach (QWebElement iframeElement, iframes) {
                QString src = iframeElement.attribute("src");
                fileIFrame.write(QString("%0").arg(src).toAscii().toBase64());
            }
            fileIFrame.close();
        }


        ///////////////////////////////////////
        // TODO: save all networkaccessmanager traffic, a custom handler required

        ///////////////////////////////////////
        // lets emit a signal that we are done
        emit webshotReady();
    FUNC_OUT;
}
